﻿using System;
using System.Data.Common;
using System.Configuration;

using LeanEngine;
using LeanEngine.Configuration;

namespace LeanEngine.Data
{
    /// <summary>
    ///  Represents a set of methods for creating instances of a provider's implementation of the data source classes.
    /// </summary>
    internal struct DataProvider
    {
        #region Declaration Members

        private static readonly DbProviderFactory DB_FACTORY = DbProviderFactories.GetFactory(DefaultConnection.ProviderName);

        /// <summary>
        /// Error code of an attempt to insert duplicate data.
        /// </summary>
        const int DUPLICATE_KEY_ERROR_CODE = -2146232060;
        const string SQL_CLIENT_PROVIDER = "System.Data.SqlClient";

        #endregion

        #region PropertyInfo Members

        /// <summary>
        /// Gets the default connection string.
        /// </summary>
        public static ConnectionStringSettings DefaultConnection
        {
            get { return AppSetting.GetConnection("defaultConnection"); }
        }

        #endregion

        #region Method Members
        
        /// <summary>
        /// Returns a new instance of the provider's class that implements the System.Data.Common.DbConnection class.
        /// </summary>
        internal static DbConnection NewConnection()
        {
            var cnn = DB_FACTORY.CreateConnection();
            cnn.ConnectionString = DefaultConnection.ConnectionString;

            return cnn;
        }

        /// <summary>
        /// Returns a new instance of the provider's class that implements the System.Data.Common.DbCommand class.
        /// </summary>
        internal static DbCommand NewCommand()
        {
            return DB_FACTORY.CreateCommand();
        }

        internal static IDataCommand NewDataCommand()
        {
            return (DataProvider.DefaultConnection.ProviderName == DataProvider.SQL_CLIENT_PROVIDER)
                ? new SqlClient.SqlClientDataCommand()
                : PluginProvider.LoadInterface<IDataCommand>();
        }

        internal static ICrudCommand NewCrudCommand()
        {
            return (DefaultConnection.ProviderName == SQL_CLIENT_PROVIDER)
                ? new SqlClient.SqlClientCrudCommand()
                : PluginProvider.LoadInterface<ICrudCommand>();
        }

        internal static ISqlTextBuilder NewSqlTextBuilder()
        {
            return (DefaultConnection.ProviderName == SQL_CLIENT_PROVIDER)
                ? new SqlClient.SqlClientTextBuilder()
                : PluginProvider.LoadInterface<ISqlTextBuilder>();
        }

        #endregion
    }
}
